package com.hifar.test.syncData.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.model.VO.IdVO;
import com.hifar.model.VO.QueryParamsVO;
import com.hifar.plat.AopOption.DictModel;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.MinioUtil;
import com.hifar.sys.PageResult;
import com.hifar.sys.SystemUtil;
import com.hifar.test.syncData.pojo.HfEnvSyncDataExportTask;
import com.hifar.test.syncData.pojo.HfEnvSyncDataImportTableInfo;
import com.hifar.test.syncData.pojo.HfEnvSyncDataImportTask;
import com.hifar.test.syncData.pojo.VO.SyncDataImportTaskDetailVO;
import com.hifar.test.syncData.service.IHfEnvSyncDataExportTaskService;
import com.hifar.test.syncData.service.IHfEnvSyncDataImportTableInfoService;
import com.hifar.test.syncData.service.IHfEnvSyncDataImportTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhuWeiWei
 * @description 数据同步导入记录
 * @date 2025/6/11 10:30
 */
@Api("数据同步导入记录")
@RestController
@RequestMapping("/api/busi/test/syncImportTask")
@Slf4j
public class HfEnvSyncDataImportTaskController {

    @Autowired
    private IHfEnvSyncDataImportTaskService syncDataImportTaskService;

    @Autowired
    private IHfEnvSyncDataImportTableInfoService importTableInfoService;


    @ApiOperation("分页列表查询")
    @PostMapping("/listPage")
    public BusiResponse listPage(@RequestBody QueryParamsVO queryParamsVO) {
        QueryParamBean<HfEnvSyncDataImportTask> queryParamBean = new QueryParamBean<>(queryParamsVO);
        queryParamBean.addColumns(HfEnvSyncDataImportTask.class);
        QueryWrapper<HfEnvSyncDataImportTask> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfEnvSyncDataImportTask> page = queryParamBean.getPage();
        queryWrapper.orderByDesc("create_time");
        Page<HfEnvSyncDataImportTask> pageData = syncDataImportTaskService.page(page, queryWrapper);
        List<HfEnvSyncDataImportTask> records = pageData.getRecords();
        for (HfEnvSyncDataImportTask record : records) {
            String filePath = record.getFilePath();
            String bucketPre = record.getBucketPre();
            Integer secretLevel = record.getSecretLevel();

            if (StringUtils.isNotBlank(filePath)) {
                String downloadFilePath = MinioUtil.getFullFilePaths(bucketPre, filePath, secretLevel);
                record.setFilePath(downloadFilePath);
            }
        }


        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }

    @ApiOperation("删除导入记录")
    @PostMapping("/delete")
    public BusiResponse delete(@RequestBody @Validated IdVO idVO) {
        String id = idVO.getId();
        if (StringUtils.isBlank(id)) {
            return BusiResponse.error("ID不能为空");
        }

        // 逻辑删除
        HfEnvSyncDataImportTask importTask = syncDataImportTaskService.getById(id);
        if (importTask == null) {
            return BusiResponse.error("导入记录不存在");
        }

        boolean result = syncDataImportTaskService.removeById(id);
        if (result) {
            return BusiResponse.ok("删除成功");
        } else {
            return BusiResponse.error("删除失败");
        }
    }

    @ApiOperation("查询导入任务详情")
    @PostMapping("/detail")
    public BusiResponse detail(@RequestBody @Validated IdVO idVO) {
        String taskId = idVO.getId();
        if (StringUtils.isBlank(taskId)) {
            return BusiResponse.error("任务ID不能为空");
        }

        // 查询任务基本信息
        HfEnvSyncDataImportTask importTask = syncDataImportTaskService.getById(taskId);
        if (importTask == null) {
            return BusiResponse.error("导入任务不存在");
        }

        // 封装详情VO
        SyncDataImportTaskDetailVO detailVO = new SyncDataImportTaskDetailVO();
        BeanUtils.copyProperties(importTask, detailVO);

        // 查询表导入详情列表
        QueryWrapper<HfEnvSyncDataImportTableInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id", taskId);
        queryWrapper.orderByAsc("create_time");
        List<HfEnvSyncDataImportTableInfo> tableInfoList = importTableInfoService.list(queryWrapper);

        log.info("查询导入任务详情，taskId: {}, 查询到 {} 条表记录", taskId, tableInfoList != null ? tableInfoList.size() : 0);
        if (tableInfoList != null && !tableInfoList.isEmpty()) {
            log.debug("表记录详情: {}", tableInfoList);
        }

        detailVO.setTableInfoList(tableInfoList);

        // 计算总插入数量、总更新数量、实际表数量和附件统计
        int totalInsertNum = 0;
        int totalUpdateNum = 0;
        int actualTableCount = 0;
        int totalFileCount = 0;
        int successFileCount = 0;
        int failFileCount = 0;

        // 分离普通表记录和附件统计记录
        List<HfEnvSyncDataImportTableInfo> normalTableList = new ArrayList<>();
        HfEnvSyncDataImportTableInfo fileImportInfo = null;

        if (tableInfoList != null) {
            for (HfEnvSyncDataImportTableInfo tableInfo : tableInfoList) {
                // 附件统计记录特殊处理（表名为__FILE_IMPORT__）
                if ("__FILE_IMPORT__".equals(tableInfo.getTableName())) {
                    fileImportInfo = tableInfo;
                    // 附件总数使用insertNum字段存储
                    if (tableInfo.getInsertNum() != null) {
                        totalFileCount = tableInfo.getInsertNum();
                    }
                    // 附件成功数使用updateNum字段存储
                    if (tableInfo.getUpdateNum() != null) {
                        successFileCount = tableInfo.getUpdateNum();
                    }
                } else {
                    // 普通表记录
                    normalTableList.add(tableInfo);
                    actualTableCount++;
                    if (tableInfo.getInsertNum() != null) {
                        totalInsertNum += tableInfo.getInsertNum();
                    }
                    if (tableInfo.getUpdateNum() != null) {
                        totalUpdateNum += tableInfo.getUpdateNum();
                    }
                }
            }
        }

        // 过滤掉附件统计记录，只显示普通表记录
        detailVO.setTableInfoList(normalTableList);

        // 计算附件失败数
        failFileCount = totalFileCount - successFileCount;

        // 使用实际导入的表数量，而不是taskCount字段
        detailVO.setTaskCount(actualTableCount);
        detailVO.setTotalInsertNum(totalInsertNum);
        detailVO.setTotalUpdateNum(totalUpdateNum);
        detailVO.setTotalFileCount(totalFileCount);
        detailVO.setSuccessFileCount(successFileCount);
        detailVO.setFailFileCount(failFileCount);

        log.info("统计结果 - 表数量: {}, 总插入: {}, 总更新: {}, 附件: {}/{}/{}",
                actualTableCount, totalInsertNum, totalUpdateNum, successFileCount, failFileCount, totalFileCount);

        return BusiResponse.OK(detailVO);
    }
}
